import { Context } from 'koa';
import { query, queryOne } from '../database/mysql';
import { Blog, Tag, Category, BlogRelation } from '../database/models';
import { utils } from '../utils/utils';
import { success, error } from '../utils/response';
import { ResponseCode } from '../config/responseCode';

/**
 * 获取博客的分类和标签信息
 */
async function getBlogRelations(blogIds: string[]): Promise<Map<string, { categories: Category[]; tags: Tag[] }>> {
  if (blogIds.length === 0) {
    return new Map();
  }

  const placeholders = blogIds.map(() => '?').join(',');
  const relations = await query<BlogRelation>(
    `SELECT * FROM blog_relations WHERE blog_id IN (${placeholders})`,
    blogIds
  );

  // 获取所有分类ID和标签ID
  const categoryIds: string[] = [];
  const tagIds: string[] = [];
  const blogRelationsMap = new Map<string, { categoryIds: string[]; tagIds: string[] }>();

  relations.forEach((relation) => {
    if (!blogRelationsMap.has(relation.blog_id)) {
      blogRelationsMap.set(relation.blog_id, { categoryIds: [], tagIds: [] });
    }
    const blogRels = blogRelationsMap.get(relation.blog_id)!;
    if (relation.relation_type === 'category') {
      blogRels.categoryIds.push(relation.relation_id);
      if (!categoryIds.includes(relation.relation_id)) {
        categoryIds.push(relation.relation_id);
      }
    } else if (relation.relation_type === 'tag') {
      blogRels.tagIds.push(relation.relation_id);
      if (!tagIds.includes(relation.relation_id)) {
        tagIds.push(relation.relation_id);
      }
    }
  });

  // 批量查询分类和标签
  const categoriesMap = new Map<string, Category>();
  if (categoryIds.length > 0) {
    const categoryPlaceholders = categoryIds.map(() => '?').join(',');
    const categories = await query<Category>(
      `SELECT * FROM categories WHERE id IN (${categoryPlaceholders})`,
      categoryIds
    );
    categories.forEach((cat) => {
      categoriesMap.set(cat.id, cat);
    });
  }

  const tagsMap = new Map<string, Tag>();
  if (tagIds.length > 0) {
    const tagPlaceholders = tagIds.map(() => '?').join(',');
    const tags = await query<Tag>(
      `SELECT * FROM tags WHERE id IN (${tagPlaceholders})`,
      tagIds
    );
    tags.forEach((tag) => {
      tagsMap.set(tag.id, tag);
    });
  }

  // 构建结果
  const result = new Map<string, { categories: Category[]; tags: Tag[] }>();
  blogIds.forEach((blogId) => {
    const rels = blogRelationsMap.get(blogId);
    const categories: Category[] = [];
    const tags: Tag[] = [];
    if (rels) {
      rels.categoryIds.forEach((catId) => {
        const cat = categoriesMap.get(catId);
        if (cat) {
          categories.push(cat);
        }
      });
      rels.tagIds.forEach((tagId) => {
        const tag = tagsMap.get(tagId);
        if (tag) {
          tags.push(tag);
        }
      });
    }
    result.set(blogId, { categories, tags });
  });

  return result;
}

/**
 * 创建博客
 */
export async function createBlog(ctx: Context): Promise<void> {
  const { title, content, summary, cover, status, category_ids, tag_ids } = ctx.request.body as {
    title?: string;
    content?: string;
    summary?: string;
    cover?: string;
    status?: number;
    category_ids?: string[]; // 分类ID数组（使用关系表）
    tag_ids?: string[]; // 标签ID数组（使用关系表）
  };

  if (!title) {
    error(ctx, ResponseCode.BAD_REQUEST, '博客标题不能为空');
    return;
  }

  if (!content) {
    error(ctx, ResponseCode.BAD_REQUEST, '博客内容不能为空');
    return;
  }

  const currentUser = ctx.state.user as any;
  const userId = currentUser.id;

  // 验证分类ID（如果提供）
  if (category_ids && category_ids.length > 0) {
    for (const categoryId of category_ids) {
      const category = await queryOne<Category>(
        'SELECT * FROM categories WHERE id = ? AND user_id = ?',
        [categoryId, userId]
      );
      if (!category) {
        error(ctx, ResponseCode.BAD_REQUEST, `分类ID ${categoryId} 不存在或不属于当前用户`);
        return;
      }
    }
  }

  // 验证标签ID（如果提供）
  if (tag_ids && tag_ids.length > 0) {
    for (const tagId of tag_ids) {
      const tag = await queryOne<Tag>(
        'SELECT * FROM tags WHERE id = ? AND user_id = ?',
        [tagId, userId]
      );
      if (!tag) {
        error(ctx, ResponseCode.BAD_REQUEST, `标签ID ${tagId} 不存在或不属于当前用户`);
        return;
      }
    }
  }

  // 创建博客
  const blogId = utils.generateUUID();
  await query(
    `INSERT INTO blogs (id, user_id, title, content, summary, cover, status)
     VALUES (?, ?, ?, ?, ?, ?, ?)`,
    [
      blogId,
      userId,
      title,
      content,
      summary || null,
      cover || null,
      status !== undefined ? status : 0,
    ]
  );

  // 创建分类关系（一个博客可以有多个分类）
  if (category_ids !== undefined) {
    if (Array.isArray(category_ids) && category_ids.length > 0) {
      for (const categoryId of category_ids) {
        if (categoryId) {
          const relationId = utils.generateUUID();
          await query(
            'INSERT INTO blog_relations (id, blog_id, relation_type, relation_id) VALUES (?, ?, ?, ?)',
            [relationId, blogId, 'category', categoryId]
          );
        }
      }
    }
  }

  // 创建标签关系（一个博客可以有多个标签）
  if (tag_ids !== undefined) {
    if (Array.isArray(tag_ids) && tag_ids.length > 0) {
      for (const tagId of tag_ids) {
        if (tagId) {
          const relationId = utils.generateUUID();
          await query(
            'INSERT INTO blog_relations (id, blog_id, relation_type, relation_id) VALUES (?, ?, ?, ?)',
            [relationId, blogId, 'tag', tagId]
          );
        }
      }
    }
  }

  const newBlog = await queryOne<Blog>('SELECT * FROM blogs WHERE id = ?', [blogId]);
  if (!newBlog) {
    error(ctx, ResponseCode.BLOG_NOT_FOUND);
    return;
  }

  // 获取分类和标签信息
  const relations = await getBlogRelations([blogId]);
  const blogData = relations.get(blogId) || { categories: [], tags: [] };
  
  success(ctx, {
    ...newBlog,
    categories: blogData.categories,
    tags: blogData.tags,
  });
}

/**
 * 更新博客
 */
export async function updateBlog(ctx: Context): Promise<void> {
  const { id, title, content, summary, cover, status, category_ids, tag_ids } = ctx.request.body as {
    id?: string;
    title?: string;
    content?: string;
    summary?: string;
    cover?: string;
    status?: number;
    category_ids?: string[]; // 分类ID数组（使用关系表）
    tag_ids?: string[]; // 标签ID数组（使用关系表）
  };

  if (!id) {
    error(ctx, ResponseCode.BAD_REQUEST, '博客ID不能为空');
    return;
  }

  const currentUser = ctx.state.user as any;
  const userId = currentUser.id;

  // 检查博客是否存在且属于当前用户
  const blog = await queryOne<Blog>('SELECT * FROM blogs WHERE id = ? AND user_id = ?', [id, userId]);
  if (!blog) {
    error(ctx, ResponseCode.BLOG_NOT_FOUND);
    return;
  }

  // 验证分类ID（如果提供）
  if (category_ids !== undefined && Array.isArray(category_ids) && category_ids.length > 0) {
    for (const categoryId of category_ids) {
      if (categoryId) {
        const category = await queryOne<Category>(
          'SELECT * FROM categories WHERE id = ? AND user_id = ?',
          [categoryId, userId]
        );
        if (!category) {
          error(ctx, ResponseCode.BAD_REQUEST, `分类ID ${categoryId} 不存在或不属于当前用户`);
          return;
        }
      }
    }
  }

  // 验证标签ID（如果提供）
  if (tag_ids !== undefined && Array.isArray(tag_ids) && tag_ids.length > 0) {
    for (const tagId of tag_ids) {
      if (tagId) {
        const tag = await queryOne<Tag>(
          'SELECT * FROM tags WHERE id = ? AND user_id = ?',
          [tagId, userId]
        );
        if (!tag) {
          error(ctx, ResponseCode.BAD_REQUEST, `标签ID ${tagId} 不存在或不属于当前用户`);
          return;
        }
      }
    }
  }

  // 更新博客信息
  const updates: string[] = [];
  const params: any[] = [];

  if (title !== undefined) {
    updates.push('title = ?');
    params.push(title);
  }
  if (content !== undefined) {
    updates.push('content = ?');
    params.push(content);
  }
  if (summary !== undefined) {
    updates.push('summary = ?');
    params.push(summary);
  }
  if (cover !== undefined) {
    updates.push('cover = ?');
    params.push(cover);
  }
  if (status !== undefined) {
    updates.push('status = ?');
    params.push(status);
  }

  if (updates.length > 0) {
    params.push(id, userId);
    await query(`UPDATE blogs SET ${updates.join(', ')} WHERE id = ? AND user_id = ?`, params);
  }

  // 更新分类关系（如果提供）
  if (category_ids !== undefined) {
    // 删除旧的关系
    await query('DELETE FROM blog_relations WHERE blog_id = ? AND relation_type = ?', [id, 'category']);
    // 创建新的关系（一个博客可以有多个分类）
    if (Array.isArray(category_ids) && category_ids.length > 0) {
      for (const categoryId of category_ids) {
        if (categoryId) {
          const relationId = utils.generateUUID();
          await query(
            'INSERT INTO blog_relations (id, blog_id, relation_type, relation_id) VALUES (?, ?, ?, ?)',
            [relationId, id, 'category', categoryId]
          );
        }
      }
    }
  }

  // 更新标签关系（如果提供）
  if (tag_ids !== undefined) {
    // 删除旧的关系
    await query('DELETE FROM blog_relations WHERE blog_id = ? AND relation_type = ?', [id, 'tag']);
    // 创建新的关系
    if (Array.isArray(tag_ids) && tag_ids.length > 0) {
      for (const tagId of tag_ids) {
        if (tagId) {
          const relationId = utils.generateUUID();
          await query(
            'INSERT INTO blog_relations (id, blog_id, relation_type, relation_id) VALUES (?, ?, ?, ?)',
            [relationId, id, 'tag', tagId]
          );
        }
      }
    }
  }

  const updatedBlog = await queryOne<Blog>('SELECT * FROM blogs WHERE id = ? AND user_id = ?', [id, userId]);
  if (!updatedBlog) {
    error(ctx, ResponseCode.BLOG_NOT_FOUND);
    return;
  }

  // 获取分类和标签信息
  const relations = await getBlogRelations([id]);
  const blogData = relations.get(id) || { categories: [], tags: [] };
  
  success(ctx, {
    ...updatedBlog,
    categories: blogData.categories,
    tags: blogData.tags,
  });
}

/**
 * 删除博客
 */
export async function deleteBlog(ctx: Context): Promise<void> {
  const { id } = ctx.request.body as { id?: string };

  if (!id) {
    error(ctx, ResponseCode.BAD_REQUEST, '博客ID不能为空');
    return;
  }

  const currentUser = ctx.state.user as any;
  const userId = currentUser.id;

  // 检查博客是否存在且属于当前用户
  const blog = await queryOne<Blog>('SELECT * FROM blogs WHERE id = ? AND user_id = ?', [id, userId]);
  if (!blog) {
    error(ctx, ResponseCode.BLOG_NOT_FOUND);
    return;
  }

  // 删除关联关系
  await query('DELETE FROM blog_relations WHERE blog_id = ?', [id]);

  // 删除博客（确保只删除属于当前用户的博客）
  await query('DELETE FROM blogs WHERE id = ? AND user_id = ?', [id, userId]);

  success(ctx, { message: '删除成功' });
}

/**
 * 查询博客列表
 */
export async function getBlogList(ctx: Context): Promise<void> {
  const { page = 1, pageSize = 10, title, category_id, status } = ctx.request.body as {
    page?: number;
    pageSize?: number;
    title?: string;
    category_id?: string; // 分类ID（通过关系表筛选）
    status?: number;
  };

  const currentUser = ctx.state.user as any;
  const userId = currentUser.id;

  // 如果提供了分类ID，需要通过关系表筛选
  let blogIds: string[] = [];
  if (category_id) {
    const categoryBlogs = await query<BlogRelation>(
      'SELECT DISTINCT blog_id FROM blog_relations WHERE relation_type = ? AND relation_id = ?',
      ['category', category_id]
    );
    blogIds = categoryBlogs.map((b) => b.blog_id);
    if (blogIds.length === 0) {
      // 如果没有找到任何博客，直接返回空结果
      success(ctx, {
        list: [],
        total: 0,
        page,
        pageSize,
      });
      return;
    }
  }

  let sql = 'SELECT * FROM blogs WHERE user_id = ?';
  const params: any[] = [userId];

  if (title) {
    sql += ' AND title LIKE ?';
    params.push(`%${title}%`);
  }
  if (category_id && blogIds.length > 0) {
    const placeholders = blogIds.map(() => '?').join(',');
    sql += ` AND id IN (${placeholders})`;
    params.push(...blogIds);
  }
  if (status !== undefined) {
    sql += ' AND status = ?';
    params.push(status);
  }

  sql += ' ORDER BY created_at DESC LIMIT ? OFFSET ?';
  const offset = (page - 1) * pageSize;
  params.push(pageSize, offset);

  const blogs = await query<Blog>(sql, params);

  // 获取所有博客的分类和标签信息
  const blogIdsList = blogs.map((b) => b.id);
  const relations = await getBlogRelations(blogIdsList);
  const blogsWithRelations = blogs.map((blog) => {
    const blogData = relations.get(blog.id) || { categories: [], tags: [] };
    return {
      ...blog,
      categories: blogData.categories,
      tags: blogData.tags,
    };
  });

  // 构建总数查询（排除分页参数）
  let countSql = 'SELECT COUNT(*) as count FROM blogs WHERE user_id = ?';
  const countParams: any[] = [userId];
  
  if (title) {
    countSql += ' AND title LIKE ?';
    countParams.push(`%${title}%`);
  }
  if (category_id && blogIds.length > 0) {
    const placeholders = blogIds.map(() => '?').join(',');
    countSql += ` AND id IN (${placeholders})`;
    countParams.push(...blogIds);
  }
  if (status !== undefined) {
    countSql += ' AND status = ?';
    countParams.push(status);
  }

  const totalResult = await queryOne<{ count: number }>(countSql, countParams);

  success(ctx, {
    list: blogsWithRelations,
    total: totalResult?.count || 0,
    page,
    pageSize,
  });
}

/**
 * 查询博客详情
 */
export async function getBlogDetail(ctx: Context): Promise<void> {
  const { id } = ctx.request.body as { id?: string };

  if (!id) {
    error(ctx, ResponseCode.BAD_REQUEST, '博客ID不能为空');
    return;
  }

  const currentUser = ctx.state.user as any;
  const userId = currentUser.id;

  const blog = await queryOne<Blog>('SELECT * FROM blogs WHERE id = ? AND user_id = ?', [id, userId]);
  if (!blog) {
    error(ctx, ResponseCode.BLOG_NOT_FOUND);
    return;
  }

  // 获取分类和标签信息
  const relations = await getBlogRelations([id]);
  const blogData = relations.get(id) || { categories: [], tags: [] };
  
  success(ctx, {
    ...blog,
    categories: blogData.categories,
    tags: blogData.tags,
  });
}

/**
 * 发布博客
 */
export async function publishBlog(ctx: Context): Promise<void> {
  const { id } = ctx.request.body as { id?: string };

  if (!id) {
    error(ctx, ResponseCode.BAD_REQUEST, '博客ID不能为空');
    return;
  }

  const currentUser = ctx.state.user as any;
  const userId = currentUser.id;

  // 检查博客是否存在且属于当前用户
  const blog = await queryOne<Blog>('SELECT * FROM blogs WHERE id = ? AND user_id = ?', [id, userId]);
  if (!blog) {
    error(ctx, ResponseCode.BLOG_NOT_FOUND);
    return;
  }

  // 更新状态为已发布
  await query('UPDATE blogs SET status = 1 WHERE id = ? AND user_id = ?', [id, userId]);

  const updatedBlog = await queryOne<Blog>('SELECT * FROM blogs WHERE id = ? AND user_id = ?', [id, userId]);
  if (!updatedBlog) {
    error(ctx, ResponseCode.BLOG_NOT_FOUND);
    return;
  }

  // 获取分类和标签信息
  const relations = await getBlogRelations([id]);
  const blogData = relations.get(id) || { categories: [], tags: [] };
  
  success(ctx, {
    ...updatedBlog,
    categories: blogData.categories,
    tags: blogData.tags,
  });
}

/**
 * 取消发布博客
 */
export async function unpublishBlog(ctx: Context): Promise<void> {
  const { id } = ctx.request.body as { id?: string };

  if (!id) {
    error(ctx, ResponseCode.BAD_REQUEST, '博客ID不能为空');
    return;
  }

  const currentUser = ctx.state.user as any;
  const userId = currentUser.id;

  // 检查博客是否存在且属于当前用户
  const blog = await queryOne<Blog>('SELECT * FROM blogs WHERE id = ? AND user_id = ?', [id, userId]);
  if (!blog) {
    error(ctx, ResponseCode.BLOG_NOT_FOUND);
    return;
  }

  // 更新状态为未发布
  await query('UPDATE blogs SET status = 0 WHERE id = ? AND user_id = ?', [id, userId]);

  const updatedBlog = await queryOne<Blog>('SELECT * FROM blogs WHERE id = ? AND user_id = ?', [id, userId]);
  if (!updatedBlog) {
    error(ctx, ResponseCode.BLOG_NOT_FOUND);
    return;
  }

  // 获取分类和标签信息
  const relations = await getBlogRelations([id]);
  const blogData = relations.get(id) || { categories: [], tags: [] };
  
  success(ctx, {
    ...updatedBlog,
    categories: blogData.categories,
    tags: blogData.tags,
  });
}

/**
 * 公开查询博客列表（无需登录，只返回已发布的博客）
 * 需要提供 user_id 参数，只返回该用户已发布的博客
 */
export async function getPublicBlogList(ctx: Context): Promise<void> {
  const { user_id, page = 1, pageSize = 10, title, category_id } = ctx.request.body as {
    user_id?: string;
    page?: number;
    pageSize?: number;
    title?: string;
    category_id?: string; // 分类ID（通过关系表筛选）
  };

  if (!user_id) {
    error(ctx, ResponseCode.BAD_REQUEST, '用户ID不能为空');
    return;
  }

  // 如果提供了分类ID，需要通过关系表筛选
  let blogIds: string[] = [];
  if (category_id) {
    const categoryBlogs = await query<BlogRelation>(
      'SELECT DISTINCT blog_id FROM blog_relations WHERE relation_type = ? AND relation_id = ?',
      ['category', category_id]
    );
    blogIds = categoryBlogs.map((b) => b.blog_id);
    if (blogIds.length === 0) {
      // 如果没有找到任何博客，直接返回空结果
      success(ctx, {
        list: [],
        total: 0,
        page,
        pageSize,
      });
      return;
    }
  }

  // 只查询指定用户已发布的博客（status = 1）
  let sql = 'SELECT * FROM blogs WHERE user_id = ? AND status = 1';
  const params: any[] = [user_id];

  if (title) {
    sql += ' AND title LIKE ?';
    params.push(`%${title}%`);
  }
  if (category_id && blogIds.length > 0) {
    const placeholders = blogIds.map(() => '?').join(',');
    sql += ` AND id IN (${placeholders})`;
    params.push(...blogIds);
  }

  sql += ' ORDER BY created_at DESC LIMIT ? OFFSET ?';
  const offset = (page - 1) * pageSize;
  params.push(pageSize, offset);

  const blogs = await query<Blog>(sql, params);

  // 获取所有博客的分类和标签信息
  const blogIdsList = blogs.map((b) => b.id);
  const relations = await getBlogRelations(blogIdsList);
  const blogsWithRelations = blogs.map((blog) => {
    const blogData = relations.get(blog.id) || { categories: [], tags: [] };
    return {
      ...blog,
      categories: blogData.categories,
      tags: blogData.tags,
    };
  });

  // 构建总数查询（排除分页参数）
  let countSql = 'SELECT COUNT(*) as count FROM blogs WHERE user_id = ? AND status = 1';
  const countParams: any[] = [user_id];
  
  if (title) {
    countSql += ' AND title LIKE ?';
    countParams.push(`%${title}%`);
  }
  if (category_id && blogIds.length > 0) {
    const placeholders = blogIds.map(() => '?').join(',');
    countSql += ` AND id IN (${placeholders})`;
    countParams.push(...blogIds);
  }

  const totalResult = await queryOne<{ count: number }>(countSql, countParams);

  success(ctx, {
    list: blogsWithRelations,
    total: totalResult?.count || 0,
    page,
    pageSize,
  });
}

/**
 * 公开查询博客详情（无需登录，只返回已发布的博客）
 * 需要提供 user_id 参数，只返回该用户已发布的博客
 */
export async function getPublicBlogDetail(ctx: Context): Promise<void> {
  const { id, user_id } = ctx.request.body as { id?: string; user_id?: string };

  if (!id) {
    error(ctx, ResponseCode.BAD_REQUEST, '博客ID不能为空');
    return;
  }

  if (!user_id) {
    error(ctx, ResponseCode.BAD_REQUEST, '用户ID不能为空');
    return;
  }

  // 只查询指定用户已发布的博客（status = 1）
  const blog = await queryOne<Blog>('SELECT * FROM blogs WHERE id = ? AND user_id = ? AND status = 1', [id, user_id]);
  if (!blog) {
    error(ctx, ResponseCode.BLOG_NOT_FOUND);
    return;
  }

  // 获取分类和标签信息
  const relations = await getBlogRelations([id]);
  const blogData = relations.get(id) || { categories: [], tags: [] };
  
  success(ctx, {
    ...blog,
    categories: blogData.categories,
    tags: blogData.tags,
  });
}

/**
 * 获取博客管理页面初始化数据（优化：一次请求获取所有数据）
 * 返回博客列表、分类列表、标签列表，减少前端请求次数
 */
export async function getBlogInitData(ctx: Context): Promise<void> {
  const { page = 1, pageSize = 10, title, category_id, status } = ctx.request.body as {
    page?: number;
    pageSize?: number;
    title?: string;
    category_id?: string;
    status?: number;
  };

  const currentUser = ctx.state.user as any;
  const userId = currentUser.id;

  // 并行获取博客列表、分类列表、标签列表
  const [blogsResult, categoriesResult, tagsResult] = await Promise.all([
    // 获取博客列表（复用 getBlogList 的逻辑）
    (async () => {
      // 如果提供了分类ID，需要通过关系表筛选
      let blogIds: string[] = [];
      if (category_id) {
        const categoryBlogs = await query<BlogRelation>(
          'SELECT DISTINCT blog_id FROM blog_relations WHERE relation_type = ? AND relation_id = ?',
          ['category', category_id]
        );
        blogIds = categoryBlogs.map((b) => b.blog_id);
        if (blogIds.length === 0) {
          return {
            list: [],
            total: 0,
            page,
            pageSize,
          };
        }
      }

      let sql = 'SELECT * FROM blogs WHERE user_id = ?';
      const params: any[] = [userId];

      if (title) {
        sql += ' AND title LIKE ?';
        params.push(`%${title}%`);
      }
      if (category_id && blogIds.length > 0) {
        const placeholders = blogIds.map(() => '?').join(',');
        sql += ` AND id IN (${placeholders})`;
        params.push(...blogIds);
      }
      if (status !== undefined) {
        sql += ' AND status = ?';
        params.push(status);
      }

      sql += ' ORDER BY created_at DESC LIMIT ? OFFSET ?';
      const offset = (page - 1) * pageSize;
      params.push(pageSize, offset);

      const blogs = await query<Blog>(sql, params);

      // 获取所有博客的分类和标签信息
      const blogIdsList = blogs.map((b) => b.id);
      const relations = await getBlogRelations(blogIdsList);
      const blogsWithRelations = blogs.map((blog) => {
        const blogData = relations.get(blog.id) || { categories: [], tags: [] };
        return {
          ...blog,
          categories: blogData.categories,
          tags: blogData.tags,
        };
      });

      // 构建总数查询（排除分页参数）
      let countSql = 'SELECT COUNT(*) as count FROM blogs WHERE user_id = ?';
      const countParams: any[] = [userId];
      
      if (title) {
        countSql += ' AND title LIKE ?';
        countParams.push(`%${title}%`);
      }
      if (category_id && blogIds.length > 0) {
        const placeholders = blogIds.map(() => '?').join(',');
        countSql += ` AND id IN (${placeholders})`;
        countParams.push(...blogIds);
      }
      if (status !== undefined) {
        countSql += ' AND status = ?';
        countParams.push(status);
      }

      const totalResult = await queryOne<{ count: number }>(countSql, countParams);

      return {
        list: blogsWithRelations,
        total: totalResult?.count || 0,
        page,
        pageSize,
      };
    })(),
    // 获取分类列表（全部，不分页）
    (async () => {
      const categories = await query<Category>(
        'SELECT * FROM categories WHERE user_id = ? ORDER BY sort_order ASC, created_at DESC',
        [userId]
      );
      return categories;
    })(),
    // 获取标签列表（全部，不分页）
    (async () => {
      const tags = await query<Tag>(
        'SELECT * FROM tags WHERE user_id = ? ORDER BY created_at DESC',
        [userId]
      );
      return tags;
    })(),
  ]);

  success(ctx, {
    blogs: blogsResult,
    categories: categoriesResult,
    tags: tagsResult,
  });
}

